package com.yeskery.nut.transaction;

import com.yeskery.nut.event.ApplicationEvent;
import com.yeskery.nut.event.ProxySmartApplicationListener;

import java.lang.reflect.Method;

/**
 * 事务事件监听器
 * @author sunjay
 * 2023/9/5
 */
public class TransactionApplicationListener extends ProxySmartApplicationListener {

    /** 事务管理器 */
    private final TransactionManager transactionManager;

    /** 事务阶段 */
    private final TransactionPhase transactionPhase;

    /**
     * 构建事务事件监听器
     * @param transactionManager 事务管理器
     * @param transactionPhase 事务阶段
     * @param type   支持的事件类型
     * @param order  顺序值
     * @param target 目标对象
     * @param method 目标方法
     */
    public TransactionApplicationListener(TransactionManager transactionManager, TransactionPhase transactionPhase,
                                          Class<? extends ApplicationEvent> type, int order, Object target, Method method) {
        super(type, order, target, method);
        this.transactionManager = transactionManager;
        this.transactionPhase = transactionPhase;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        switch (transactionPhase) {
            case BEFORE_COMMIT: transactionManager.registerBeforeCommitTransactionCallback(() -> super.onApplicationEvent(event)); break;
            case AFTER_COMMIT: transactionManager.registerAfterCommitTransactionCallback(() -> super.onApplicationEvent(event)); break;
            case AFTER_ROLLBACK: transactionManager.registerAfterRollbackTransactionCallback(() -> super.onApplicationEvent(event)); break;
            case AFTER_COMPLETION: transactionManager.registerAfterCompletedTransactionCallback(() -> super.onApplicationEvent(event)); break;
            default: throw new TransactionException("Unknown Transaction Phase.");
        }
    }
}
